//
// Club Controller
//
var mongoose   = require('mongoose');
var geocoder   = require('node-geocoder').getGeocoder('google', 'https', {apiKey: 'AIzaSyCvXjC9t8o0MDG89LrcAzImA_lcaeSKObs', formatter: null});
var ObjectID   = mongoose.Schema.Types.ObjectId;

module.exports = function(app) {

   // Search clubs
   app.route('/clubs/list')
      .post(function(req, res){
         var keyword = req.body.keyword;
         keyword = keyword.replace(/(?:\*)/g, ' ');
         var regex = new RegExp(["",keyword,""].join(""),"i");
         Domain.Club.find({name: regex}).populate('creator').populate('members').exec(function(err, clubs){
            if(err) throw err
            res.render('clubs/list', {user: req.user, clubs: clubs});
         });
      });

   // Create Club
   app.route('/clubs/create')
      .get(app.isLoggedIn, function(req, res){
         if(!req.user.club) // && req.user.role %% (req.user.role=='manager' || req.user.role=='admin'))
            res.render('clubs/create', {user: req.user, csrf: req.csrfToken()});
         else
            res.redirect('/clubs/detail/' + req.user.club._id);
      })

      .post(app.isLoggedIn, function(req, res){
         var club          = new Domain.Club();
         club.name         = req.body.name;
         club.description  = req.body.description;
         club.createddate  = Date.now();
         club.creator      = req.user;
         club.members.push(req.user);
         club.zipcode      = req.body.zipcode;
         geocoder.geocode(req.body.zipcode, function(err, loc){
            if(err) throw err;
            club.lat       = loc[0].latitude;
            club.lng       = loc[0].longitude;
            club.save(function(err){
               if(err) throw err;
               req.user.club = club._id;
               req.user.joinedclubs.push(club);
               req.user.save(function(err){
                  if(err) throw err;
                  res.redirect('/clubs/detail/' + club._id);
               });
            });
         });
      });

   // Club Detail
   app.route('/clubs/detail/:id')
      .get(function(req, res){
         var id = req.params.id;
         Domain.Club.findById(id).populate('creator').populate('members').exec(function(err, club){
            if(err)     throw err
            res.render('clubs/detail', {user: req.user, club: club});
         });
      });

   // Join Club - TODO: use POST
   app.route('/clubs/join/:id')
      .get(app.isLoggedIn, function(req, res){
         var id = req.params.id;
         var club;

         // 1) Check if you already joined
         if(req.user.joinedclubs){  // pre: joinedclubs are already populated!!!
            for(var i = 0; i < req.user.joinedclubs.length; i++){
               if(req.user.joinedclubs[i]._id.toString() == id) return res.redirect('/clubs/detail/' + id);
            }
         }
         Domain.Club.findById(id).exec(function(err, doc){
            if(err) throw err;
            club = doc;
            // 2) club.members.push
            Domain.Club.update({_id: club._id}, {$push: {members: req.user._id} }, function(err, num){
               if(err) throw err;
               // 3) user.joinedclubs.push
               Domain.User.update({ _id : req.user._id }, {$push: {joinedclubs: club._id} }, function(errr, num){
                  if(err) throw err;
                  res.redirect('/clubs/detail/' + id);
               });
            });
         });
      });

   // Leave Club - TODO: use POST
   app.route('/clubs/leave/:id')
      .get(app.isLoggedIn, function(req, res){
         var id = req.params.id;
         var club;
         Domain.Club.findById(id).exec(function(err, doc){
            if(err) throw err;
            club = doc;
            // 1) club.members.pull
            Domain.Club.update({_id: club._id}, {$pull: {members: req.user._id} }, function(err, num){
               if(err) throw err;
               // 2) user.joinedclubs.pull
               Domain.User.update({ _id : req.user._id }, {$pull: {joinedclubs: club._id} }, function(errr, num){
                  if(errr) throw errr;
                  res.redirect('/clubs/detail/' + id);
               });
            });
         });
      });




};




